<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>

      <el-row>
        <el-col>
          <el-button type="primary" plain @click="addRightsShowClick">新增权限</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="tableInfo.rightsList"
        border
        stripe
        row-key='id'
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column label="权限名称" prop="rightsName"></el-table-column>
        <el-table-column label="上级权限" prop="parentName"></el-table-column>
        <el-table-column label="路径" prop="path"></el-table-column>
        <el-table-column label="权限等级" prop="rightsGrade">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.rightsGrade === '1'">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.rightsGrade === '2'">二级</el-tag>
            <el-tag type="warning" v-else-if="scope.row.rightsGrade === '3'">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" size="mini" round @click="handleUpdateShowClick(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" round @click="handleDelClick(scope.row)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>

<!-- 分页 -->
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="tableInfo.total"
        class="elPagiNation"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
      >
      </el-pagination>

    </el-card>

    <!-- 新增权限Dialog -->
    <el-dialog
      title="新增权限"
      :visible.sync="addRightsDialogVisible"
      width="30%"
    >

      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="父级权限" prop="parentId">
          <el-tree
            :data="treeData"
            :props="treeProps"
            node-key="id"
            ref="treeDataRef"
            show-checkbox
            check-strictly
            @node-click="handleNodeClick"
            @check-change="handleCheckChange"
          />
        </el-form-item>

        <el-form-item label="权限名称" prop="rightsName">
          <el-input v-model="addForm.rightsName"></el-input>
        </el-form-item>

        <el-form-item label="权限地址" prop="path">
          <el-input v-model="addForm.path"></el-input>
        </el-form-item>

        <el-form-item label="权限等级" prop="rightsGrade">
          <el-select v-model="addForm.rightsGrade" placeholder="请选择权限等级">
            <el-option label="一级" value="1"></el-option>
            <el-option label="二级" value="2"></el-option>
            <el-option label="三级" value="3"></el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormCancelClick">取 消</el-button>
        <el-button type="primary" @click="addFormSubmitClick">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改权限Dialog -->
    <el-dialog
      title="修改权限"
      :visible.sync="updateDialogVisible"
      width="30%"
      @close="handleUpdateDialogClose"
    >
      <span style="color: red;font-weight: bold">现：权限仅支持三级，请谨慎修改！</span>
      <el-form
        :model="updateForm"
        :rules="updateRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="父级权限" prop="parentId">
          <el-tree
            :data="treeData"
            :props="treeProps"
            node-key="id"
            ref="updateTreeDataRef"
            default-expand-all
            show-checkbox
            check-strictly
            @node-click="handleUpdateNodeClick"
            @check-change="handleUpdateCheckChange"
            class="updateTree"
          />
        </el-form-item>

        <el-form-item label="权限名称" prop="rightsName">
          <el-input v-model="updateForm.rightsName"></el-input>
        </el-form-item>

        <el-form-item label="权限地址" prop="path">
          <el-input v-model="updateForm.path"></el-input>
        </el-form-item>

        <el-form-item label="权限等级" prop="rightsGrade" >
          <el-select
            v-model="updateForm.rightsGrade"
            placeholder="请选择权限等级"
            disabled
          >
            <el-option label="一级" value="1"></el-option>
            <el-option label="二级" value="2"></el-option>
            <el-option label="三级" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleUpdateCancleClick">取 消</el-button>
        <el-button type="primary" @click="handleUpdateConfirmClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Rights",
  data() {
    return {
      // 权限列表
      tableInfo: {
        rightsList: [],
        total: 0
      },
      // 查询对象
      queryInfo: {
        pageNum: 1,
        pageSize: 8
      },
      // 新增权限Dialog 展示与否
      addRightsDialogVisible: false,
      // 新增权限表单
      addForm: {
        parentId: '',
        rightsName: '',
        path: '',
        rightsGrade: ''
      },
      // 所有的权限
      rightsAll: [],
      // 权限的等级
      rightsGradeSelect: '',
      // 新增权限的form验证
      addRules: {
        rightsName: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
        ],
        path: [
          {required: true, message: '请输入权限路径', trigger: 'blur'}
        ],
      },
      // 树形权限结构
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'rightsName',
      },
      treeCheckId: '',
      // 控制修改页面的展示与否
      updateDialogVisible: false,
      // 修改form
      updateForm: {},
      // 修改表单的验证规则
      updateRules: {},
      // 修改页面的树形结构选中的Id
      updateTreeCheckId: ''
    }
  },
  created() {
    // 获取所有的权限
    this.getRightsList();
    this.addForm.rightsGrade = '1';
  },
  methods: {
    // 分页 页数改变
    async handleCurrentChange(pageNum) {
      this.queryInfo.pageNum= pageNum;
      await this.getRightsList();
    },
    // 用户点击上一页按钮改变当前页后触发
    async handlePrevClick(pageNum) {
      this.queryInfo.pageNum= pageNum;
      await this.getRightsList();
    },
    // 用户点击下一页按钮改变当前页后触发
    async handleNextClick(pageNum) {
      this.queryInfo.pageNum= pageNum;
      await this.getRightsList();
    },
    // 获取权限列表
    async getRightsList() {
      const {data: res} = await this.$http.get('/rights/getAllRights/tree/page', {
        params: this.queryInfo
      });
      if (!res.status) return this.$message.error(res.message);
      this.tableInfo.rightsList = res.data.treeRights;
      this.tableInfo.total = res.data.total;
    },
    // 获取权限列表树形结构
    async getRightsTree() {
      const {data: res} = await this.$http.get('/rights/getAllRights/tree', {
        params: this.queryInfo
      });
      if (!res.status) return this.$message.error(res.message);
      this.treeData = res.data;
    },
    // 打开新增权限页面
    async addRightsShowClick() {
      await this.getRightsTree();
      this.addRightsDialogVisible = true;
    },
    // 新增页面取消按钮点击
    addFormCancelClick() {
      this.$refs.addFormRef.resetFields();
      this.addForm = {};
      this.addRightsDialogVisible = false;
    },
    // 新增权限提交
    addFormSubmitClick() {
      this.$refs.addFormRef.validate(async valid => {
        this.addForm.parentId = this.treeCheckId;
        if (!valid) return this.$message.error("验证未通过！");
        const {data: res} = await this.$http.post(`/rights/addRights`, this.addForm);
        if (!res.status) return this.$message.error(res.message);
        this.$message.success(res.message);
        await this.getRightsList();
        this.addForm = {}
        this.$refs.treeDataRef.setCheckedKeys(['']);
        this.treeCheckId = '';
        this.addRightsDialogVisible = false;
      })
    },
    // 新增页面树形结构的点击事件
    handleNodeClick(data) {
      if (data.id === this.treeCheckId) {
        this.treeCheckId = '';
        this.$refs.treeDataRef.setCheckedKeys(['']);
      }
    },
    // 新增页面中树形结构值改变事件
    handleCheckChange(data, checked) {
      if (checked === true) {
        this.treeCheckId = data.id;
        this.$refs.treeDataRef.setCheckedKeys([data.id]);
      } else {
        if (this.treeCheckId === data.id) {
          this.$refs.treeDataRef.setCheckedKeys([data.id]);
        }
      }
    },
    // 点击修改
    async handleUpdateShowClick(row) {
      await this.getRightsTree();
      this.updateTreeCheckId = row.id;
      this.updateForm = row;
      this.updateDialogVisible = true;
      this.$nextTick(() => this.$refs.updateTreeDataRef.setCheckedKeys([row.id]));
      },
    // 修改页面树形结构的点击事件
    handleUpdateNodeClick(data) {
      if (data.id === this.updateTreeCheckId) {
        this.updateTreeCheckId = '';
        this.$refs.updateTreeDataRef.setCheckedKeys(['']);
      }
    },
    // 修改页面中树形结构值改变事件
    handleUpdateCheckChange(data, checked) {
      if (checked === true) {
        this.updateTreeCheckId = data.id;
        this.$refs.updateTreeDataRef.setCheckedKeys([data.id]);
      } else {
        if (this.treeCheckId === data.id) {
          this.$refs.updateTreeDataRef.setCheckedKeys([data.id]);
        }
      }
    },
    // 修改页面关闭事件
    handleUpdateDialogClose () {
      this.updateForm = {};
      this.$refs.updateTreeDataRef.setCheckedKeys(['']);
      this.updateTreeCheckId = '';
    },
    // 更新页面取消按钮点击事件
    handleUpdateCancleClick () {
      this.handleUpdateDialogClose();
      this.updateDialogVisible = false;
    },
    // 更新页面确定按钮点击事件
    async handleUpdateConfirmClick() {
      this.updateForm.parentId = this.updateTreeCheckId;
      const {data:res} = await this.$http.put(`/rights/updateRights`, this.updateForm);

      if (!res.status) return this.$message.error(res.message);
      this.$message.success(res.message);
      this.handleUpdateDialogClose();
      this.updateDialogVisible = false;
    },
    // 删除按钮点击事件
    async handleDelClick(row) {

      // 弹框提示是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }

      if (row.children != null) return this.$message.error("禁止删除，该节点含有字权限！");

      const {data:res} = await this.$http.delete(`/rights/delRights`, {params:{'id': row.id}});

      if(!res.status) return this.$message.error(res.message);
      await this.getRightsList();
      this.$message.success(res.message);
    }

  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 300px;
}

.el-select {
  width: 300px;
}

.el-pagination {
  text-align: center;
}
.elPagiNation {
  text-align: center;
}
</style>
